#include <ballade/network/ssl_socket.h>

namespace Ballade
{
	namespace Network
	{
		
		SSLSocket::SSLSocket(SSLContext& context) : _context(context)
		{
			_ssl = NULL;
		}
		
		SSLSocket::SSLSocket(const char *ipaddr, const unsigned short port, SSLContext& context) : Socket(ipaddr, port), _context(context)
		{
			_ssl = NULL;
		}
		
		SSLSocket::~SSLSocket() 
		{
		}
		
		void SSLSocket::connect(const char *ipaddr, const unsigned short port)
		{
			setIPAddress(ipaddr);
			setPort(port);
			connect();
		}
		
		void SSLSocket::connect()
		{
			Socket::connect();
			int err = 0;
			_ssl = SSL_new(_context.getContext());
			if(_ssl == NULL) throw SocketError("Create SSL socket failed");
			
			SSL_set_fd(_ssl, getSocketDescriptor());
			err = SSL_connect(_ssl);	
			if(err < 0) throw SocketError("Binding SSL failed");
			
// 			setInputStream(new SSLInputStream(_ssl));
// 			setOutputStream(new SSLOutputStream(_ssl));
		}
		
		void SSLSocket::close()
		{
			if(_ssl) 
			{
				SSL_shutdown(_ssl);
				Socket::close();
				SSL_free(_ssl);
				_ssl = NULL;
			}
		}

	}
}